<template>
  <div class="multiple-card-container service-card-container">
    <!-- start 按钮组 -->
    <div class="btn-wrap">
      <el-button
        @click="openChooseServiceDialog"
        v-if="allowCreate"
        type="primary"
        size="mini"
        plain
      >{{$t('task.detail.components.addService')}}</el-button>
      <el-button
        v-if="isExport"
        @click="exportEvent"
        type="primary"
        size="mini"
        plain
      >{{$t('common.base.export')}}</el-button>
    </div>
    <!-- end 按钮组 -->

    <!-- start 服务项目列表 -->
    <service-card-list
      :data="data"
      :columns="columns"
      :list-loading="loading"
      :allow-edit="allowEdit"
      :edit-unit-price="editUnitPrice"
      :internationalGray="internationalGray"
    />
    <!-- end 服务项目列表 -->

    <!-- start 选择服务项目弹窗 -->
    <choose-service-dialog
      ref="chooseServiceDialog"
      :colums="columns"
      @submit="addService"
    />
    <!-- end 选择服务项目弹窗 -->
  </div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
/* components */
import ServiceCardList from './ServiceCardList';
import ChooseServiceDialog from '@src/modules/task/editAllot/components/PartSeviceList/components/ChooseServiceDialog.vue';
/* mixin */
import cardMixin from './../CardMixin.js';
/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
/* model */
import { PART_SERVICE_LIST_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
export default {
  name: 'service-card',
  mixins: [cardMixin],
  data() {
    return {
      // 服务项目列表数据
      data: [],
      internationalGray: false,
      loading: true
    }
  },
  computed: {
    /** 
    * @description 服务项目附加组件列表项
    */
    columns() {
      let fields = this.card.fields.filter(field => field.enabled && !field.isHidden)

      // 是否有删除权限
      if (this.allowDelete) {
        fields.push({
          displayName: this.$t('common.base.operation'),
          fieldName: 'action',
          minWidth: '60px'
        })
      }

      // 设置服务项目名称列宽
      fields.forEach(field => {
        if (field.fieldName == 'name') {
          field.minWidth = '120px';
        }
        if (this.internationalGray && field.fieldName == 'salePrice'&& this.editUnitPrice) {
          field.minWidth = '170px';
        }
      })

      // 服务项目 是否展示终端销售价和小计
      if(!this.serviceProviderShowPrice) {
        fields = fields.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'total')
      }

      return fields;
    },
    // 回执中的服务项目的是否开启了区域定价
    serviceItemEnableRegionalPricing() {
      const ret = (this.shareData.receiptFields || []).find(item => item.fieldName === 'serviceIterm') || {}
      return ret?.setting?.useRegionalPricing || false;
    }
  },
  mounted() {
    this.getInventoryByCardId();
    const { internationalGray } = useFormMultiLanguage()
    this.internationalGray = internationalGray
  },
  methods: {
    /** 
    * @description 查询服务清单列表数据
    */
    async getInventoryByCardId() {
      try {
        const params = {
          cardId: this.card.cardId,
          taskId: this.task.id
        }
        this.loading = true;
        let res = await TaskApi.getInventoryByCardId(params);
        if (!res.success || !res.result) return;

        this.data = res.result || [];
        this.data.forEach(item => {
          item.type = item.sparepartType; // 类别
          if(this.internationalGray) item.salePriceCurrency = item.salePriceCurrency || 'CNY'
        })

        this.$eventBus.$emit('task_service_list_update', { data: this.data, fields: this.card.fields });
      } catch(err) {
        console.error('service getInventoryByCardId err', err)
      } finally {
        this.loading = false;
      }
    },
    /** 打开添加服务项目弹窗 */
    openChooseServiceDialog() {
      this.$refs.chooseServiceDialog.open();
    },
    /** 打开添加服务项目弹窗 */
    openAddonsDialogAuto() {
      if(this.allowCreate) {
        this.$refs.chooseServiceDialog.open();
      }
    },
    /** 添加服务项目 */
    addService(data) {
      if (data.length == 0) return this.$platform.alert(this.$t('task.tip.serviceTip'));

      // 是否超过最大限制
      let isOverLimit = this.data.length + data.length > PART_SERVICE_LIST_MAX_LENGTH;
      if (isOverLimit) return this.$platform.alert(PART_SERVICE_LIST_MAX_LENGTH_MESSAGE);

      this.$refs.chooseServiceDialog.togglePending(true);

      let baseTaskInventories = [];
      data.forEach(item => {
        baseTaskInventories.push({
          taskId: this.task.id,
          taskNo: this.task.taskNo,
          cardId: this.card.cardId,
          relationId: item.id,
          relationName: item.name,
          preNum: item.preNum,
          salePrice: item.salePrice || 0,
          salePriceCurrency: item.salePriceCurrency || 'CNY',
          type: 2
        })
      })

      TaskApi.addTaskInventory({ baseTaskTypeId: this.task.templateId, baseTaskInventories })
        .then(res => {
          if (res.success) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.tip.addSuccess')
            })

            this.getInventoryByCardId();
            this.$refs.chooseServiceDialog.close();

            this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
          } else {
            this.$platform.alert(res.message);
            this.$refs.chooseServiceDialog.togglePending();
          }
        })
        .catch(err => {
          this.$refs.chooseServiceDialog.togglePending();
        })
    }
  },
  components: {
    [ServiceCardList.name]: ServiceCardList,
    [ChooseServiceDialog.name]: ChooseServiceDialog
  }
}
</script>
